package com.lkd.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lkd.dto.UserDto;
import com.lkd.entity.Role;
import com.lkd.entity.User;
import com.lkd.exception.BusinessException;
import com.lkd.mapper.UserMapper;
import com.lkd.service.IRoleService;
import com.lkd.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lkd.utils.JwtUtil;
import com.lkd.vo.LoginUserVo;
import com.lkd.vo.PageBean;
import com.lkd.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zzy
 * @since 2025-10-10
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private IRoleService roleService;

    @Override
    public LoginUserVo login(String loginName, String password) {
        //查询用户信息
        User user = userMapper.selectByLoginName(loginName);
        if (user == null || !user.getPassword().equals(password)) {
            throw new BusinessException("用户名或密码错误");
        }

//        if (user == null || !user.getPassword().equals(DigestUtils.md5DigestAsHex(password.getBytes()))) {
//            return null; // 用户不存在或密码错误
//        }

        // 校验用户状态
        if (user.getStatus() == 0) { // 0 表示停用状态
            throw new BusinessException("用户名或密码错误");
        }

        // 构造登录结果
        LoginUserVo loginUserVo = new LoginUserVo();
        loginUserVo.setUserId(user.getId());
        loginUserVo.setUserName(user.getUserName());
        loginUserVo.setRoleCode(user.getRoleCode());
        loginUserVo.setRegionId(user.getRegionId());

        Map<String, Object> claims = new HashMap<>();
        claims.put("id", user.getId());
        claims.put("username", user.getUserName());

        // 添加这行代码 - 定义token过期时间（例如：24小时）
        long ttlMillis = 24 * 60 * 60 * 1000L;  // 24小时的毫秒数

        String jwt = JwtUtil.createJWT(user.getSecret(), ttlMillis, claims);

        loginUserVo.setToken(jwt);
        return loginUserVo;

    }

    /**
     * 人员搜索
     *
     * @param userDto
     * @return
     */
    @Override
    public PageBean<UserVo> search(UserDto userDto) {

//        Page<User> page = new Page<>(userDto.getPageIndex(), userDto.getPageSize());
//
//        Page<UserVo> search = this.baseMapper.search(page, userDto);
//
//        return new PageBean<>(search);
//    }

        Page<User> userPage = new Page<>(userDto.getPageIndex(),userDto.getPageSize());

        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<User>()
                .like(ObjectUtil.isNotNull(userDto.getUserName()),User::getUserName, userDto.getUserName());

        Page<User> page = this.page(userPage, wrapper);

        List<UserVo> collect = page.getRecords().stream().map(item -> {
            Role byId = roleService.getById(item.getRoleId());
            UserVo userVo = new UserVo();
//            Role role = new Role();
            BeanUtil.copyProperties(item, userVo);

//            role.setRoleId(byId.getRoleId());
//            role.setRoleCode(byId.getRoleCode());
//            role.setRoleName(byId.getRoleName());
//            userVo.setRole(role);
            userVo.setRole(byId);
            return userVo;
        }).collect(Collectors.toList());

        PageBean<UserVo> pageBean = new PageBean<>();
        pageBean.setCurrentPageRecords(collect);
        pageBean.setTotalPage(page.getPages());
        pageBean.setTotalCount(page.getTotal());
        pageBean.setPageIndex((int)page.getCurrent());
        pageBean.setPageSize((int)page.getSize());
        return pageBean;
    }
}
